package team.kirohuji.controller.attendance;

import javax.annotation.Resource;
import javax.jms.Topic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import team.kirohuji.domain.attendance.Affiche;
import team.kirohuji.repository.jpa.attendance.AfficheRepository;
import team.kirohuji.service.attendance.AfficheService;
import team.kirohuji.service.message.ProducerService;
import team.kirohuji.utils.R;

@RestController
@RequestMapping("/affiche")
public class AfficheController {
	private static final Logger logger = LoggerFactory.getLogger(AfficheController.class);

	
	@Resource
	public AfficheService afficheService;

	@Resource
	public ProducerService producerService;
	
	@Autowired
	public AfficheRepository afficheRepository;
	
	public Topic topic;

	@RequestMapping(value = "/lists", method = RequestMethod.GET)
	public Page<Affiche> getAttendanceLists(@RequestParam(value = "page", defaultValue = "0") Integer page,
			@RequestParam(value = "size", defaultValue = "5") Integer size) {
		Sort sort = new Sort(Direction.DESC, "afficheId");
		Pageable pageable = new PageRequest(page, size, sort);
		return afficheRepository.findAll(pageable);
	}

	@RequestMapping(value = "/save", method = RequestMethod.GET)
	public Affiche save(@ModelAttribute Affiche affihce) {
		return afficheRepository.save(affihce);
	}

	@RequestMapping(value = "/delete/{afficheId}", method = RequestMethod.GET)
	public R delete(@PathVariable Integer afficheId) {
		if (afficheId != null || afficheId != 0) {
			afficheRepository.deleteById(afficheId);
			return R.ok();
		} else {
			return R.error();
		}
	}

	@RequestMapping(value = "/{afficheId}", method = RequestMethod.GET)
	public Affiche findOne(@PathVariable Integer afficheId) {
		return afficheRepository.getOne(afficheId);
	}
	@RequestMapping(value = "/message/{topicName}/{message}", method = RequestMethod.GET)
	public R findOne(@PathVariable String topicName,@PathVariable String message) {
		if(topic!=null) {
			topic=producerService.setTopicName(topicName);
		}
		producerService.sendTopicMessage(topic, message);
		return R.ok();
	}
}
